/*
 * @Author: cys
 * @Date: 2018-07-23 10:36:04
 * @Last Modified by: leo
 * @Last Modified time: 2018-11-19 08:57:54
 * 多选表格视图混合
 */
import { Component, Vue, Watch } from "vue-property-decorator";
@Component
export default class TableViewMulSelectMix extends Vue {
  public nodeKey: string = "id"; // 数据项种的唯一key值
  public data!: any[]; // 表格数据
  public selectedData: Array<{
    id: number;
    name: string;
    [propName: string]: any;
  }> = []; // 初始化传入选中的数据nodeKey集合
  public selected: any = {}; // 已选map数据 key=对应数据nodeKey
  public async fetchData() { }
  // 初始化选择项 data-table数据
  public initSelected(data: any[]) {
    const map: any = {};
    data.forEach((item: any) => {
      map[item[this.nodeKey]] = item;
    });
    this.selectedData.forEach((item: any) => {
      if (map.hasOwnProperty(item.id)) {
        this.selected[item.id] = map[item.id];
      } else {
        this.selected[item.id] = item;
      }
    });
    // 因为table混合限制 执行第一页时会触发iniSelected方法, 所以赋值后清空初始值
    this.selectedData = [];
  }
  // 翻页设置选择项 data-table数据
  public setSelected(data: any[]) {
    const nd = this.$refs.Table as any;
    data.forEach((item: any) => {
      if (this.selected.hasOwnProperty(item[this.nodeKey])) {
        console.log("this.nodeKey: ", item[this.nodeKey]);
        // 更新选中数据
        this.$set(this.selected, item[this.nodeKey], item);
        this.$nextTick(() => {
          nd.$refs.refName.toggleRowSelection(item, true);
        });
      }
    });
  }
  // 点击table 复选按钮时触发事件
  public selectChange(selection: any, row: any) {
    // 取消选中的
    if (this.selected.hasOwnProperty(row[this.nodeKey])) {
      this.$delete(this.selected, row[this.nodeKey]);
    }
    selection.forEach((item: any) => {
      this.$set(this.selected, item[this.nodeKey], item);
    });
  }
  // 点击全选时触发
  public selectAllChange(selection: any) {
    // 当页全选
    if (selection.length) {
      selection.forEach((item: any) => {
        this.$set(this.selected, item[this.nodeKey], item);
      });
    } else {
      this.data.forEach((item: any) => {
        if (this.selected.hasOwnProperty(item[this.nodeKey])) {
          this.$delete(this.selected, item[this.nodeKey]);
        }
      });
    }
  }
  // 删除tag
  public closeTag(tagkey: string) {
    const nd = this.$refs.Table as any;
    for (const key in this.selected) {
      if (key === tagkey) {
        nd.$refs.refName.toggleRowSelection(this.selected[key], false);
        this.$delete(this.selected, key);
      }
    }
  }
  // 监听data变化 设置table选中
  @Watch("data")
  private dataChange(newData: any[]) {
    this.initSelected(newData);
    this.setSelected(newData);
  }
  // 重新赋值操作
  @Watch("value")
  private watchValue(
    val: Array<{ id: number; name: string; [propName: string]: any }>
  ) {
    const nd = this.$refs.Table as any;
    nd.$refs.refName.clearSelection();
    this.selected = {};
    this.selectedData = val;
    this.initSelected(this.data);
    this.setSelected(this.data);
    // this.fetchData();
  }
}
